package com.olap.starter.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipUtils {


    /**
     * 导入
     *
     * @return Workbook
     */

    public static File transferToFile(MultipartFile multipartFile) {
//        选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile("temp", filename.length > 1 ? filename[1] : filename[0] + ".");
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static Map<String, StringBuilder> readZipEntry(InputStream inputStream) throws IOException {
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        ZipEntry zipEntry;
        Map<String, StringBuilder> map = new HashMap<>();
        BufferedReader in = null;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String name = zipEntry.getName().toString().trim();
           /* StringBuilder stringBuilder = map.getOrDefault(name, new StringBuilder());
            byte[] buffer = new byte[1024];
            int length;
            while ((length = zipInputStream.read(buffer)) > 0) {
                stringBuilder.append(new String(buffer, 0, length));
            }
*/
            in = new BufferedReader(new InputStreamReader(zipInputStream, "UTF-8"));
            StringBuilder stringBuilder = map.getOrDefault(name, new StringBuilder());
            String line = "";
            while ((line = in.readLine()) != null) {
                stringBuilder.append(line);
            }
            map.put(name,stringBuilder);
        }
        inputStream.close();
        zipInputStream.closeEntry();
        zipInputStream.close();
        return map;
    }

    public static Map<String, StringBuilder> readString(MultipartFile multipartFile) throws IOException {
        File file = transferToFile(multipartFile);
        FileInputStream fileInputStream = null;
        if (file.exists()) {
            try {
                fileInputStream = new FileInputStream(file);
                return readZipEntry(fileInputStream);
            } finally {
                file.delete();
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            }
        }
        return null;
    }

}
